#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include <fcntl.h>
#include <json-c/json.h>

using namespace std;
#define PORT 9090
#define Size 1024

struct FileName
{
    FileName(const char *name, size_t flag)
    {
        memcpy(m_name, name,1024);
        m_flag = flag;
    }
    char m_name[Size];
    size_t m_flag;
};

int main()
{
    // 创建通信文件描述符
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 使用TCP协议
    if (sockfd == -1)
    {
        perror("socket create error:");
        _exit(-1);
    }

    // 连接服务器
    sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof(serverAddress));
    // 地址族
    serverAddress.sin_family = AF_INET; // IPv4
    // 端口
    serverAddress.sin_port = htons(PORT);
    // 服务器IP
    const char *serverIp = "192.168.248.128";
    inet_pton(AF_INET, serverIp, &(serverAddress.sin_addr.s_addr));

    if (connect(sockfd, (const sockaddr *)&serverAddress, sizeof(serverAddress)) == -1)
    {
        perror("connect error:");
        close(sockfd);
        _exit(-1);
    }

    char data[Size] = {0};
    cout << "请输入发送信息 :" << endl;
    cin >> data;
    FileName filename(data, -1);
    send(sockfd, &filename, sizeof(FileName), 0);
    int readfd = open(data, O_RDONLY);
    if (readfd == -1)
    {
        perror("open file error:");
        close(sockfd);
        _exit(-1);
    }
    /* 可通过lseek函数计算得到文件的大小 */
    int offset = lseek(readfd, 0, SEEK_END);
    lseek(readfd, 0, SEEK_SET);

    sleep(1);
    int i = 0;
    while (i < offset)
    {
        memset(data, 0, sizeof(data));
        int bytesRead = read(readfd, data, sizeof(data));
        if (bytesRead <= 0)
        {
            perror("read file error:");
            break;
        }
        FileName fileCont(data, i);
        send(sockfd, &fileCont, sizeof(FileName), 0);
        i += bytesRead;
        usleep(10000);
    }

    close(readfd);
    close(sockfd);

    pause();
    return 0;
}
